package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"wjp/ginandvue/common"
	"wjp/ginandvue/model"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//获取authorization header
		tokenString := c.GetHeader("Authorization")

		if tokenString ==" "|| !strings.HasPrefix(tokenString,"Bearer"){
			c.JSON(http.StatusUnauthorized,gin.H{"code":401,"msg":"权限不足"})
			c.Abort()
			return
		}
		tokenString = tokenString[7:]
		token,claims,err := common.ParseToken(tokenString)
		if err != nil ||!token.Valid{
			c.JSON(http.StatusUnauthorized,gin.H{"code":401,"msg":"权限不足"})
			c.Abort()
			return
		}
		//验证通过后获取claims中的uid
		userId := claims.UserId
		Db := common.GetDb()
		var user model.User
		Db.First(&user,userId)

		if user.ID == 0{
			c.JSON(http.StatusUnauthorized,gin.H{"code":401,"msg":"权限不足"})
			c.Abort()
			return
		}
		//用户存在时
		c.Set("user",user)
		c.Next()

	}
}
